package com.dearbinge.data.service.impl.orderTable;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.dearbinge.data.api.commodity.CommodityCommissionService;
import com.dearbinge.data.api.commodityspec.CommoditySpecService;
import com.dearbinge.data.api.orderTable.OrderTableService;
import com.dearbinge.data.dao.OrderDetailTableMapper;
import com.dearbinge.data.dao.OrderTableMapper;
import com.dearbinge.data.dao.ShopManageMapper;
import com.dearbinge.data.dao.TransactionFlowMapper;
import com.dearbinge.data.dao.UserWalletMapper;
import com.dearbinge.data.dao.cart.CartMapper;
import com.dearbinge.data.dao.commodity.CommodityCommentPicMapper;
import com.dearbinge.data.dao.commodity.CommodityCommentShopScoreMapper;
import com.dearbinge.data.pojo.commodity.CommodityCommentPicDO;
import com.dearbinge.data.pojo.commodity.CommodityCommentShopScoreDO;
import com.dearbinge.data.pojo.commodity.dto.CommodityCommissionResultDTO;
import com.dearbinge.data.pojo.commodity.vo.CommodityCommentPicResponseVO;
import com.dearbinge.data.pojo.commodityspec.CommoditySpec;
import com.dearbinge.data.pojo.orderDetailTable.OrderDetailTable;
import com.dearbinge.data.pojo.orderTable.OrderTable;
import com.dearbinge.data.pojo.shopManage.ShopManage;
import com.dearbinge.data.pojo.transactionFlow.TransactionFlow;
import com.dearbinge.utils.AddressUtil;
import com.dearbinge.utils.Base64Util;
import com.dearbinge.utils.BeanMapperUtil;
import com.dearbinge.utils.KdniaoTrackQueryAPI;
import com.dearbinge.utils.PageResult;
@Transactional
@SuppressWarnings("all")
@Service(value = "orderTableService")
public class OrderTableServiceImpl implements OrderTableService {

    @Autowired
    private OrderTableMapper orderTableMapper;
    @Autowired
    private OrderDetailTableMapper orderDetailTableMapper;
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private ShopManageMapper shopManageMapper;
    @Autowired
    private CommodityCommissionService commodityCommissionService;
    @Autowired
    private CommoditySpecService commoditySpecService;
    @Autowired
    private CommodityCommentShopScoreMapper commodityCommentShopScoreMapper;
    @Autowired
    private TransactionFlowMapper transactionFlowMapper;
    @Autowired
    private UserWalletMapper userWalletMapper;
    @Autowired
    private CommodityCommentPicMapper commodityCommentPicMapper;

    @Override
    public Integer update(OrderTable orderTable) {
        Integer dataCode = orderTableMapper.update(orderTable);
        return dataCode;
    }

    @Override
    public Integer insert(OrderTable orderTable) {
        Integer dataCode = orderTableMapper.insert(orderTable);
        return orderTable.getId();
    }

    @Override
    public Integer delete(Integer id) {
        Integer dataCode = orderTableMapper.delete(id);
        return dataCode;
    }

    @Override
    public PageResult<List<Object>> getPage(String messageSpecific,String userType , String type,String orderId,String userId, Integer orderStatus, Integer assessType,Integer isDeleted, Integer pageNo, Integer pageSize) {
        pageNo = (null == pageNo || pageNo < 1) ? 1 : pageNo;
        pageSize = (null == pageSize || pageSize < 0) ? 10 :pageSize;
        Page page = new Page(pageNo,pageSize);
        Integer count = orderTableMapper.count(userType,orderId,userId,orderStatus,assessType,isDeleted,page);
        List<Map<String,Object>> mapList = orderTableMapper.getPage(userType,orderId,userId,orderStatus,assessType,isDeleted,page);
        List<Object> ll = new ArrayList<Object>();
        for (int index = 0;index < mapList.size();index++){
            Map<String,Object> map = new HashMap<String,Object>();
            String orderid = mapList.get(index).get("oId").toString();
            List<Map<String,Object>> list = orderTableMapper.getCommodity(type,orderid);
            if(type.equals("1")){//App调用如果都发布了秀场就不显示订单
            	if(StringUtils.isEmpty(list)){
            		mapList.remove(index);
            	}
            }
            if(!StringUtils.isEmpty(messageSpecific)&&messageSpecific.equals("1")){
				try {
					KdniaoTrackQueryAPI api = new KdniaoTrackQueryAPI();
					String orderTracesByJson = api.getOrderTracesByJson("STO","7704621386512");
					net.sf.json.JSONObject json = net.sf.json.JSONObject.fromObject(orderTracesByJson);
					net.sf.json.JSONArray fromObject = net.sf.json.JSONArray.fromObject(json.get("Traces"));
					mapList.get(index).put("logisticsNews", fromObject.get(0));//物流信息
				} catch (Exception e) {
					e.printStackTrace();
				}
            }
            map.put("commodity",mapList.get(index));
            map.put("order",list);
            ll.add(map);
        }
        Integer max = count % pageSize == 0 ? count / pageSize : count / pageSize +1;
        PageResult<List<Object>> pageResult = new PageResult<List<Object>>(ll,max);
        pageResult.setMaxPageSize(max);
        return pageResult;
    }

    @Override
    public List<Object> getByUserId(String orderNum) {
        List<Object> list = new ArrayList<Object>();
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("aOrder",null);
        map.put("commodityMessage",null);
        Map<String,Object> mapList = orderTableMapper.getByUserId(orderNum);
        if (mapList != null){
            String oId = mapList.get("oId").toString();
            List<Map<String,Object>> listMap = orderTableMapper.getCommodity("",oId);
            map.put("aOrder",mapList);
            map.put("commodityMessage",listMap);
            list.add(map);
        }
        return list;
    }

    @Override
    public Integer updateStatus(String orderNum, Integer orderStatus) {
    	if(orderStatus==3){//确认收货
    		//如果是代理卖货添加卖货人佣金
    		OrderTable byNumber = orderTableMapper.getByNumber(orderNum);
    		if(byNumber.getIsDistribution()==0){
    			List<OrderDetailTable> listByOrderId = orderDetailTableMapper.listByOrderId(byNumber.getId());
    			for(int i= 0;i<listByOrderId.size();i++){
    				OrderDetailTable orderDetailTable = listByOrderId.get(i);
    				//交易流水表
    				TransactionFlow transactionFlow = new TransactionFlow();
    				transactionFlow.setMoney(orderDetailTable.getShowMoney());
    				transactionFlow.setTfType(0);
    				transactionFlow.setUserId(orderDetailTable.getSellUserId());
    				transactionFlow.setSource(3);
    				transactionFlow.setFtStatus(0);
    				transactionFlow.setIsDeleted(false);
    				transactionFlowMapper.insert(transactionFlow);
    				//钱包
    				userWalletMapper.updateMoneyByUserId(orderDetailTable.getSellUserId(),orderDetailTable.getShowMoney());
    			}
    		}

    	}
        Integer dataCode = orderTableMapper.updateStatus(orderNum,orderStatus);
        return dataCode;
    }

    @Override
    public Integer deliverGoods(String expressNum,String orderNum,String orderCompanyCode,String orderStatus,String expressName) {
    	Integer dataCode = orderTableMapper.deliverGoods(expressNum,orderNum,orderCompanyCode,orderStatus,expressName);
    	return dataCode;
    }

    @Override
    public Map<String, String> getCommodityByOrderNo(String orderNum) {
    	Map map = new HashMap<String, String>();
    	try {
    		List<Object> commodityByOrderNo = orderTableMapper.getCommodityByOrderNo(orderNum);
        	String orderId = null;
        	for(int i=0;i<commodityByOrderNo.size();i++){
        		Map object = (Map) commodityByOrderNo.get(i);
        		//配合前端返回的数据
        		object.put("hpchek", "false");
        		object.put("zpchek", "false");
        		object.put("cpchek", "false");
        		object.put("niming", "0");
        		object.put("statechek", "false");
        		orderId = (String) object.get("order_id");
        	}
        	map.put("commodityByOrderNo", commodityByOrderNo);
        	CommodityCommentShopScoreDO byOrderId = commodityCommentShopScoreMapper.getByOrderId(Integer.valueOf(orderId));
    		if(!StringUtils.isEmpty(byOrderId)){
    			map.put("isCommentShop", "true");//评论过店铺
    		}else{
    			map.put("isCommentShop", "false");//没评论过店铺
    		}
		} catch (Exception e) {
			e.printStackTrace();
		}
    	return map;
    }

    @Override
    public Integer updateStatusByWechatNumber(String orderNum, Integer orderStatus) {
    	Integer dataCode = orderTableMapper.updateStatusByWechatNumber(orderNum,orderStatus);
    	return dataCode;
    }

    @Override
    public BigDecimal selectTotalMonryByWechatNumber(String wechatNumber) {
    	return orderTableMapper.selectTotalMonryByWechatNumber(wechatNumber);
    }

	@Override
	public String addOrUpdate(JSONObject parseObject) {
		String wechatNumber = null;//微信订单编号
		com.alibaba.fastjson.JSONArray OrderTableDtoList = JSON.parseArray(parseObject.getString("data"));
		try {
			for (int i = 0; i < OrderTableDtoList.size(); i++) {
				com.alibaba.fastjson.JSONArray orderObject = JSON.parseArray(OrderTableDtoList.get(i).toString());
				long timeMillis = System.currentTimeMillis();
				int i1 = (int) ((Math.random() * 9 + 1) * 100000);
				wechatNumber = "UW"+timeMillis+""+i1;
				Integer dataCode = null;//订单id
				String sellUserId = "";
				String userId = "";
				String isDistribution = "";
				for(int j = 0; j < orderObject.size(); j++){
					OrderTable orderTable = new OrderTable();
					if(j==0){
						//插入订单
						Map object = (Map) orderObject.get(j);
						timeMillis = System.currentTimeMillis();
						i1 = (int) ((Math.random() * 9 + 1) * 100000);
						orderTable.setNumber(timeMillis+""+i1);// 订单编号
						orderTable.setWechatNumber(wechatNumber);//微信订单编号
						orderTable.setOrderStatus(0);// 0 待付款 1 待发货 2 待收货 3 待评价4失效订单
						orderTable.setBusinessType("1");// 0 待付款 1 待发货 2 待收货 3 待评价4失效订单
						orderTable.setAssessType(0);// 是否评价（0：未评价  1：已评价）
						orderTable.setIsDeleted(false);
						if(!StringUtils.isEmpty(object.get("consigneeMobile"))){
							orderTable.setConsigneeMobile(object.get("consigneeMobile").toString());
						}
						if(!StringUtils.isEmpty(object.get("consigneeName"))){
							orderTable.setConsigneeName(object.get("consigneeName").toString());
						}
						if(!StringUtils.isEmpty(object.get("addressId"))){
							orderTable.setAddressId(object.get("addressId").toString());
						}
						orderTable.setShopId(object.get("shopId").toString());
						ShopManage byId = shopManageMapper.getById(Integer.valueOf(object.get("shopId").toString()));
						orderTable.setSellerId(byId.getUserId());//卖家id（店家）
						orderTable.setUserId(object.get("userId").toString());
						userId = object.get("userId").toString();
						sellUserId= byId.getUserId();
						dataCode = orderTableMapper.insert(orderTable);
						dataCode = orderTable.getId();
						System.out.println("asd");
					}else{
						com.alibaba.fastjson.JSONArray bbb = JSON.parseArray(orderObject.get(j).toString());
						BigDecimal primaryPrice = new BigDecimal("0");//订单原价
						BigDecimal preferentialPrice = new BigDecimal("0");//订单成交价
						for(int k = 0; k < bbb.size(); k++){
							//插入订单明细
							Map object2 = (Map) bbb.get(k);
							OrderDetailTable orderDetailTable = new OrderDetailTable();
							orderDetailTable.setOrderId(dataCode);
							orderDetailTable.setCommodityId(object2.get("commodityId").toString());
							orderDetailTable.setShopNum(Integer.valueOf(object2.get("total").toString()));//商品数量
							orderDetailTable.setIsDeleted(true);

							//查询比例
							CommodityCommissionResultDTO discount = commodityCommissionService.getDiscount(Integer.valueOf(object2.get("commodityId").toString()));
							//查询商品
							CommoditySpec selectById = commoditySpecService.selectById(Integer.valueOf(object2.get("commoditySpecId").toString()));
							//transactionPrice 传过来是单件优惠后的价格
							orderDetailTable.setPreferentialPrice(new BigDecimal(object2.get("transactionPrice").toString()).multiply(new BigDecimal(object2.get("total").toString())));//成交价格 (原价X折扣)
							orderDetailTable.setPrimaryPrice(selectById.getRetailPrice());//商品原价
							orderDetailTable.setShowMoney(discount.getSendShowPct().multiply(selectById.getRetailPrice().multiply(new BigDecimal(object2.get("total").toString()))).setScale(2, BigDecimal.ROUND_UP));//发布秀场金额
							orderDetailTable.setLikeMonry(discount.getRedEnvelopePct().multiply(selectById.getRetailPrice().multiply(new BigDecimal(object2.get("total").toString()))).setScale(2, BigDecimal.ROUND_UP));//点赞红包金额
							orderDetailTable.setCommission(discount.getCommissionPct().multiply(selectById.getRetailPrice().multiply(new BigDecimal(object2.get("total").toString()))).setScale(2, BigDecimal.ROUND_UP));//佣金（代理费）
							orderDetailTable.setSource(object2.get("source").toString());
							isDistribution = object2.get("source").toString();
							if(object2.get("source").toString().equals("0")){//source 商品来源 0代理 1非代理
								orderDetailTable.setSellUserId(object2.get("sellUserId").toString());
								sellUserId = object2.get("sellUserId").toString();
							}else{
								orderDetailTable.setSellUserId(sellUserId);
							}

							orderDetailTable.setCommoditySpecId(object2.get("commoditySpecId").toString());//规格id
							orderDetailTable.setCommoditySpecDesc(object2.get("commoditySpecName").toString());//规格描述
							orderDetailTable.setRedNumber(10);//默认红包数量
							orderDetailTable.setIsRelease("2");//1已发布秀场2未发布秀场
							orderDetailTable.setRedMoney(discount.getSendShowPct().multiply(selectById.getRetailPrice()));//默认红包数量
							orderDetailTable.setCreateBy(userId);
							orderDetailTable.setSotreimg(object2.get("sotreimg").toString());
							orderDetailTable.setCommodityName(object2.get("commodityName").toString());
							orderDetailTable.setCommentStatus(0);
							Integer insert = orderDetailTableMapper.insert(orderDetailTable);
							//删除购物车
							if(!StringUtils.isEmpty(object2.get("id"))){
								cartMapper.deleteCart(Integer.valueOf(object2.get("id").toString()));
							}
							//累加统计订单表的总原价和总成交价
							primaryPrice = primaryPrice.add(primaryPrice.add(selectById.getRetailPrice()));
							preferentialPrice = preferentialPrice.add(preferentialPrice.add(new BigDecimal(object2.get("transactionPrice").toString())));



						}
						//更新订单原价  成交价
						orderTable.setId(dataCode);
						orderTable.setIsDistribution(Integer.valueOf(isDistribution));//是否分销订单0代理 1非代理
						orderTable.setCreateBy(sellUserId);//卖货人id
						orderTable.setPrimaryPrice(primaryPrice);
						orderTable.setPreferentialPrice(preferentialPrice);
						dataCode = orderTableMapper.update(orderTable);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
		}
		return wechatNumber;
	}

	/**
	 *根据卖家id查询待评价的商品
	 */
	@Override
    public PageResult<List<Object>> getCommodityByUserId(String userId , Integer pageNo, Integer pageSize) {
        pageNo = (null == pageNo || pageNo < 1) ? 1 : pageNo;
        pageSize = (null == pageSize || pageSize < 0) ? 10 :pageSize;
        Page page = new Page(pageNo,pageSize);
        Integer count = 0;
//        Integer count = orderTableMapper.count(userId );
        List<Map<String , String>> mapList = orderTableMapper.getCommodityByUserId(userId,page);
        List<Object> ll = new ArrayList<Object>();
        for (int index = 0;index < mapList.size();index++){
        	Map<String, String> map = mapList.get(index);
        	map.put("name", Base64Util.decodeData(map.get("name").toString()));
        	ll.add(map);
        	//
        	Integer valueOf = Integer.valueOf(String.valueOf(map.get("commodityCommentId")));
        	List<CommodityCommentPicDO> comment = commodityCommentPicMapper.listByCommodityCommentId(valueOf,Integer.valueOf(1));
        	String imagesUrl = "";
            if (comment == null || comment.size() == 0) {
            	map.put("imagesUrl", "");
            }else{
            	//拼接ip地址
            	for (CommodityCommentPicDO commodityCommentPicDO : comment) {
            		String address = AddressUtil.spliceAddress(commodityCommentPicDO.getPicUrl());
            		commodityCommentPicDO.setPicUrl(address);
            		imagesUrl+=","+address;
            	}
            	map.put("imagesUrl",imagesUrl);
            }
        }
        Integer max = count % pageSize == 0 ? count / pageSize : count / pageSize +1;
        PageResult<List<Object>> pageResult = new PageResult<List<Object>>(ll,max);
        pageResult.setMaxPageSize(max);
        return pageResult;
    }
}
